<template>
    <div class="photos-manage">
        <div class="header-actions">
            <el-button type="primary" @click="showAddDialog">
                <el-icon>
                    <Plus />
                </el-icon>添加照片
            </el-button>
        </div>

        <!-- 照片列表 -->
        <el-table v-loading="loading" :data="photoList" style="width: 100%">
            <el-table-column label="预览图" width="120">
                <template #default="{ row }">
                    <el-image 
                        :src="row.url"
                        :preview-src-list="[row.url]"
                        fit="cover"
                        class="preview-image"
                        :initial-index="0"
                        :preview-teleported="true"
                        :lazy="true"
                        referrerPolicy="no-referrer"
                        :hide-on-click-modal="false"
                        @error="handleImageError"
                    >
                        <template #error>
                            <div class="image-error">
                                <el-icon><Picture /></el-icon>
                                <span>加载失败</span>
                            </div>
                        </template>
                        <template #placeholder>
                            <div class="image-placeholder">
                                <el-icon><Loading /></el-icon>
                            </div>
                        </template>
                    </el-image>
                </template>
            </el-table-column>

            <el-table-column prop="url" label="图片地址" min-width="300">
                <template #default="{ row }">
                    <el-input v-model="row.url" disabled class="url-input">
                        <template #append>
                            <el-button @click="copyUrl(row.url)">复制</el-button>
                        </template>
                    </el-input>
                </template>
            </el-table-column>

            <el-table-column prop="category" label="分类" width="120">
                <template #default="{ row }">
                    <el-tag>{{ row.category }}</el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="isPrivate" label="私密" width="80">
                <template #default="{ row }">
                    <el-tag :type="row.isPrivate ? 'danger' : 'success'">
                        {{ row.isPrivate ? '是' : '否' }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="createTime" label="添加时间" width="180">
                <template #default="{ row }">
                    {{ formatDate(row.createTime) }}
                </template>
            </el-table-column>

            <el-table-column prop="description" label="描述" min-width="200">
                <template #default="{ row }">
                    <el-tooltip :content="row.description" placement="top" :hide-after="0">
                        <span class="description-text">{{ row.description }}</span>
                    </el-tooltip>
                </template>
            </el-table-column>

            <el-table-column prop="order" label="排序" width="100" />

            <el-table-column label="操作" fixed="right" width="150">
                <template #default="{ row }">
                    <el-button-group>
                        <el-button type="primary" link @click="editPhoto(row)">
                            <el-icon>
                                <Edit />
                            </el-icon>编辑
                        </el-button>
                        <el-button type="danger" link @click="deletePhoto(row)">
                            <el-icon>
                                <Delete />
                            </el-icon>删除
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                :page-sizes="[12, 24, 36, 48]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 添加/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="editingPhoto ? '编辑照片' : '添加照片'" width="500px">
            <el-form ref="formRef" :model="photoForm" :rules="rules" label-width="80px">
                <el-form-item label="图片地址" prop="url">
                    <el-input v-model="photoForm.url" placeholder="请输入图片URL地址">
                        <template #append>
                            <el-button @click="previewImage">预览</el-button>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item v-if="photoForm.url" label="预览">
                    <el-image :src="photoForm.url" fit="cover" class="url-preview" :preview-teleported="true"
                        loading="lazy" referrerPolicy="no-referrer" @error="handlePreviewError">
                        <template #error>
                            <div class="image-error">
                                <el-icon>
                                    <Picture />
                                </el-icon>
                                <span>加载失败</span>
                            </div>
                        </template>
                        <template #placeholder>
                            <div class="image-placeholder">
                                <el-icon>
                                    <Loading />
                                </el-icon>
                            </div>
                        </template>
                    </el-image>
                </el-form-item>

                <el-form-item label="分类" prop="category">
                    <el-select v-model="photoForm.category" placeholder="请选择分类">
                        <el-option v-for="category in categories" :key="category" :label="category" :value="category" />
                    </el-select>
                </el-form-item>

                <el-form-item label="私密照片">
                    <el-switch v-model="photoForm.isPrivate" />
                </el-form-item>

                <el-form-item label="描述" prop="description">
                    <el-input v-model="photoForm.description" type="textarea" rows="3" placeholder="请输入照片描述" />
                </el-form-item>

                <el-form-item label="排序">
                    <el-input-number v-model="photoForm.order" :min="0" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Picture, Loading } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { photoApi } from '@/http/apis/photos'
import type { Photo, PhotoForm, PhotoListParams, PhotoListResponse } from '@/http/apis/photos'

// 状态定义
const loading = ref(false)
const photoList = ref<Photo[]>([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const dialogVisible = ref(false)
const editingPhoto = ref<Photo | null>(null)
const formRef = ref<FormInstance>()

const categories = ref([
    '风景', '人像', '美食', '旅行', '日常', '私密'
])

const photoForm = ref<PhotoForm>({
    url: '',
    category: '',
    isPrivate: false,
    description: '',
    order: 0
})

const rules: FormRules = {
    url: [
        { required: true, message: '请输入图片URL地址', trigger: 'blur' },
        { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
    ],
    category: [{ required: true, message: '请选择分类', trigger: 'change' }],
    description: [{ required: true, message: '请输入照片描述', trigger: 'blur' }]
}

// 获取照片列表
const fetchPhotos = async () => {
    loading.value = true
    try {
        const params: PhotoListParams = {
            page: currentPage.value,
            pageSize: pageSize.value
        }

        const response = await photoApi.getAdminPhotoList(params)
        console.log('API Response:', response); // Log the response for debugging

        // Check if response is valid and has the expected structure
        if (response && response.code === 200 && response.data && Array.isArray(response.data.list)) {
            photoList.value = response.data.list as Photo[]; // Access the list property
            total.value = response.data.total; // Set total from the response
        } else {
            ElMessage.error('获取照片列表失败: 数据格式不正确');
        }
    } catch (error) {
        ElMessage.error('获取照片列表失败')
    } finally {
        loading.value = false
    }
}

// 复制URL
const copyUrl = (url: string) => {
    navigator.clipboard.writeText(url)
        .then(() => ElMessage.success('复制成功'))
        .catch(() => ElMessage.error('复制失败'))
}

// 预览图片
const previewImage = () => {
    if (!photoForm.value.url) {
        ElMessage.warning('请先输入图片地址')
        return
    }
    // URL预览逻辑已通过el-image组件自动处理
}

// 修改图片错误处理方法
const handleImageError = (error: Error) => {
    console.error('Image load failed:', error)
}

const handlePreviewError = () => {
    ElMessage.warning('图片预览失败，但链接可能仍然有效')
}

// 编辑照片
const editPhoto = (photo: Photo) => {
    editingPhoto.value = photo
    photoForm.value = {
        url: photo.url,
        category: photo.category,
        isPrivate: photo.isPrivate,
        description: photo.description,
        order: photo.order
    }
    dialogVisible.value = true
}

// 删除照片
const deletePhoto = async (photo: Photo) => {
    try {
        await ElMessageBox.confirm('确定要删除这张照片吗？', '提示', {
            type: 'warning'
        })

        const response = await photoApi.deletePhoto(photo.id)
        if (response.code === 200) {
            ElMessage.success('删除成功')
            fetchPhotos()
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 表单提交
const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const submitData = { ...photoForm.value }
                
                let response
                if (editingPhoto.value) {
                    response = await photoApi.updatePhoto(editingPhoto.value.id, submitData)
                } else {
                    response = await photoApi.addPhoto(submitData)
                }

                if (response.code === 200) {
                    ElMessage.success(editingPhoto.value ? '更新成功' : '添加成功')
                    dialogVisible.value = false
                    fetchPhotos()
                }
            } catch (error) {
                ElMessage.error(editingPhoto.value ? '更新失败' : '添加失败')
            }
        }
    })
}

// 分页方法
const handleSizeChange = (val: number) => {
    pageSize.value = val
    fetchPhotos()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    fetchPhotos()
}

// 显示添加对话框
const showAddDialog = () => {
    editingPhoto.value = null
    photoForm.value = {
        url: '',
        category: '',
        isPrivate: false,
        description: '',
        order: 0
    }
    dialogVisible.value = true
}

const formatDate = (date: string) => {
    return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
    fetchPhotos()
})
</script>

<style scoped>
.photos-manage {
    width: 100%;
    height: 100%;
    padding: 20px;
}

.header-actions {
    margin-bottom: 20px;
}

.preview-image {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    overflow: hidden;
}

.url-preview {
    width: 200px;
    height: 200px;
    border-radius: 4px;
}

.url-input {
    font-size: 12px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-input-group__append) {
    padding: 0;
}

:deep(.el-input-group__append button) {
    border: none;
    margin: 0;
    height: 100%;
}

.description-text {
    display: inline-block;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 添加错误和加载状态样式 */
.image-error,
.image-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #909399;
    font-size: 12px;
}

.image-error .el-icon,
.image-placeholder .el-icon {
    font-size: 20px;
    margin-bottom: 8px;
}
</style>
